package com.cloud.phone.task.tiktok;

import android.content.Intent;
import android.os.Handler;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.cloud.phone.base.BaseApp;
import com.cloud.phone.bean.AppInfo;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.task.BaseTask;
import com.cloud.phone.task.MsgTaskManger;
import com.cloud.phone.task.TaskManager;
import com.cloud.phone.task.bean.ApkInfo;
import com.cloud.phone.task.bean.ApkStatus;
import com.cloud.phone.task.bean.ChatMsgList;
import com.cloud.phone.task.bean.MsgTaskBean;
import com.cloud.phone.task.bean.PhoneAndLoginInfo;
import com.cloud.phone.task.bean.ServerInnerDataBean;
import com.cloud.phone.task.bean.ServerTaskDataBean;
import com.cloud.phone.task.bean.UpdateInfoHandler;
import com.cloud.phone.task.bean.UserInfo;
import com.cloud.phone.task.taskCongfig.FindIdResouresConfig;
import com.cloud.phone.task.taskCongfig.TaskTypeConfig;
import com.cloud.phone.tools.AccessibilityTool;
import com.cloud.phone.tools.LogUtils;
import com.cloud.phone.tools.MyUtils;
import com.cloud.phone.utils.AccessibilityUtil;
import com.cloud.phone.utils.AppUtils;
import com.cloud.phone.view.TsUtils;
import com.cloud.phone.web_activity.NormalWebActivity;
import com.cloud.phone.websocket.WebsocketUtil;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class TikTokTask extends BaseTask {
    public boolean isResetTikTok=false;
    public TickTokTaskDealTools tickTokTaskDealTools;
    TickTokTaskDealTools.OnUserInfoGetListener onUserInfoGetListener;
    public int beAttentionAutoReplayAccountIndex = 0;
    public List<ChatMsgList> hasBeAttentionAccount = new ArrayList<>();
    private String taoSe = "com.android.taose2024";
    private String currentEmailCode = "";
    private long requestEmailTime = 0;
    public static boolean isJumpToWebOnce;//是否已经跳转过一次web5页面

    @Override
    public void onTaskErr() {
        if (tickTokTaskDealTools != null) {
            tickTokTaskDealTools.nextIndex = 0;
        }
        TaskManager.isRegisterTaskDoing=false;
        super.onTaskErr();
    }

    @Override
    public void onTaskFinish() throws InterruptedException {
        if (tickTokTaskDealTools != null) {
            tickTokTaskDealTools.nextIndex = 0;
        }
        isResetTikTok=false;
        TaskManager.isRegisterTaskDoing=false;
        closeTikTokOrBackToMainApp();
        super.onTaskFinish();
    }


    public void closeTikTokOrBackToMainApp() throws InterruptedException {
        AccessibilityUtil.killApp(service,Constants.tiktokPackageName);
    }

    /**
     * 写触发这个无障碍事件时需要执行的事件
     */
    @Override
    public void doTask() throws InterruptedException {
        MsgTaskManger.showLog("开始做任务了··任务类型："+currentTaskType);
        if (tickTokTaskDealTools == null) {
            tickTokTaskDealTools = new TickTokTaskDealTools(this);
        }
        tickTokTaskDealTools.isForceStop=false;
        //只处理状态为运行开始的
        //设置状态为运行中，防止被新来的节点刷新事件覆盖
        onTaskRunning();
        //主线程
        //处理本次节点的对应流程，每个流程结束后都应该更改task对应的状态
        dealWithTask();
    }





    private void dealWithTask() throws InterruptedException {
        tickTokTaskDealTools.closeCenterTipsDialog();
        tickTokTaskDealTools.closeDialogAndSwipe();
        if(FindIdResouresConfig.permissionPackage.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
            tickTokTaskDealTools.allowPermission();
            Thread.sleep(2000);
            changeTaskStatusToStart();
            return;
        }
        if (AccessibilityTool.getInstance().checkIsEnterInTikTok(service)) {
            //已在tiktok页面
            try {
                dealWithTask(getTaskType());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if(TaskManager.getInstance().getCurrentTask()==null||service==null){
                return;
            }
            String pkgName=AccessibilityTool.getInstance().getCurrentPagePackageName(service);
            MsgTaskManger.showLog(dateFormat.format(new Date())+"-TiktokTask中未在tiktokApp中：taskType="+getTaskType()+"/当前app包名："+pkgName);
            if(MyUtils.isEmpty(pkgName)){
                MsgTaskManger.showLog("获取不到当前包名，重新刷新当前task状态");
                Thread.sleep(2000);
                changeTaskStatusToStart();
                return;
            }
            //不在tiktok页面时
            if (currentTaskType == TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO) {
                if (!AppUtils.Companion.isAppInstall(BaseApp.app.getApplicationContext(), Constants.tiktokPackageName)) {
                    LogUtils.e("未安装tiktok，tiktok信息获取结束");
                    //当前不在tiktok页面且并未安装tiktok，tiktok信息获取结束了
                    createCurrentUpdateInfo(null,2,true);
                    sendMsgToServer();
                    onTaskFinish();
                }
            } else {
                if (currentTaskType == TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_LIKE_BY_LINK
                        || currentTaskType == TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_COMMENT_BY_LINK) {
                    if (!BaseApp.app.getPackageName().equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))) {
                        //变更状态为开始状态
                        changeTaskStatusToStart();
                    }
                } else {
                    if (AppUtils.Companion.isAppInstall(BaseApp.app.getApplicationContext(), Constants.tiktokPackageName)) {
                        if (currentTaskType != TaskTypeConfig.TIKTOK_TASK_AUTO_REGISTER) {
                            AppUtils.Companion.launchApp(BaseApp.app.getApplicationContext(), Constants.tiktokPackageName);
                            Thread.sleep(2000);
                            changeTaskStatusToStart();
                        }else{
                            if(TaskManager.isRegisterTaskDoing){
                                return;
                            }
                            MsgTaskManger.dealWithAutoRegisterLauncher(this);
                        }
                    }
                }
            }
        }
    }


    public UserInfo getCurrentUserInfo() {
        return TaskManager.getInstance().currentTiktokUserInfo;
    }


    public boolean checkIsCurrentUserSameAsServerUser() {
        if(taskStatus==BaseTask.STOP){
            return false;
        }
        if (getCurrentUserInfo() != null && getCurrentUserInfo().getAccount().equals(serverTaskDataBean.getAccountWithUserName())) {
            LogUtils.i("用户名一致，无需切换账户");
            return true;
        }
        lastTaskType = currentTaskType;
        LogUtils.e("更新任务类型：" + currentTaskType);
        currentTaskType = TaskTypeConfig.TIKTOK_GET_USER_INFO;
        onUserInfoGetListener = new TickTokTaskDealTools.OnUserInfoGetListener() {
            @Override
            public void onUserInfoGet(UserInfo userInfo) {
                if (userInfo == null) {
                    onTaskErr("用户信息获取失败");
                } else {
                    TaskManager.getInstance().currentTiktokUserInfo = userInfo;
                    currentTaskType = lastTaskType;
                    lastTaskType = TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO;
                    changeTaskStatusToStart();
                }
            }
        };
        changeTaskStatusToStart();
        return false;
    }


    private int getTaskType() {
//        currentTaskType = TaskTypeConfig.TEST;
        return currentTaskType;
    }


    private void dealWithTask(int taskType) throws InterruptedException {
        MsgTaskManger.showLog("处理类型"+taskType+"的任务");
        switch (taskType) {
            case TaskTypeConfig.TIKTOK_CHECK_IS_LOGIN:
                //判断是否在首页
                tickTokTaskDealTools.checkIsLogin(null);
                break;
            case TaskTypeConfig.TIKTOK_GET_USER_INFO:
                if(taskStatus==BaseTask.STOP){
                    return;
                }
                //获取用户信息---前提是已登录
                tickTokTaskDealTools.getUserInfo(onUserInfoGetListener, serverTaskDataBean.getAccountWithUserName());
                break;
            case TaskTypeConfig.TIKTOK_AUTO_LOOK_VIDEO:
                showLogAndTsPrint("普通养号任务开始>>开始");
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                //普通养号
                tickTokTaskDealTools.autoLookVideo(serverTaskDataBean.getDuration() * 60 * 1000, serverTaskDataBean.getLikePercent(), serverTaskDataBean.getAttentionPercent(), serverTaskDataBean.getCommentPercent());
                break;
            case TaskTypeConfig.TIKTOK_SEARCH_AUTO_LOOK_VIDEO:
                showLogAndTsPrint("关键词养号任务开始>>开始");
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                //关键字养号
                doKeywordsAutoLookVideo();
                break;
            case TaskTypeConfig.TIKTOK_TASK_ATTENTION_USER:
                showLogAndTsPrint("关注用户任务>>开始");
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                //关注某个用户
                tickTokTaskDealTools.attentionSingleUser(serverTaskDataBean.getDealWithUserName());
                break;
            case TaskTypeConfig.TIKTOK_TASK_GET_USER_FAN_LIST:
            case TaskTypeConfig.TIKTOK_TASK_GET_CHAT_TO_USER_FANS_LIST:
                showLogAndTsPrint("获取粉丝列表任务>>开始");
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                //获取用户粉丝列表
                tickTokTaskDealTools.getUserFanList(serverTaskDataBean.getFollowAccount());
                break;
            case TaskTypeConfig.STOP_CURRENT_TASK:
                //停止当前任务
                onTaskStop();
                break;
            case TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_LIKE_BY_LINK:
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                if (!isJumpToWebOnce) {
                    if (Constants.tiktokPackageName.equals(tickTokTaskDealTools.getCurrentPagePackageName())) {
                        AccessibilityUtil.killApp(service,Constants.tiktokPackageName);
                    }
                    //跳转到对应H5页面
                    jumpToNormalWebAc();
                    Thread.sleep(2000);
                    //将任务改为之前的对应任务
                    changeTaskStatusToStart();
                    isJumpToWebOnce = true;
                    return;
                }
                showLogAndTsPrint("单个作品点赞任务>>开始");
                //链接跳转单个作品点赞
                tickTokTaskDealTools.singleWorksLike(serverTaskDataBean.getDuration());
                break;
            case TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_COMMENT_BY_LINK:
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                if (!isJumpToWebOnce) {
                    if (Constants.tiktokPackageName.equals(tickTokTaskDealTools.getCurrentPagePackageName())) {
                        AccessibilityUtil.killApp(service,Constants.tiktokPackageName);
                    }
                    //跳转到对应H5页面
                    jumpToNormalWebAc();
                    Thread.sleep(2000);
                    //将任务改为之前的对应任务
                    changeTaskStatusToStart();
                    isJumpToWebOnce = true;
                    return;
                }
                showLogAndTsPrint("单个作品评论任务>>开始");
                //链接跳转单个作品评论
                tickTokTaskDealTools.singleWorksComment(serverTaskDataBean.getDuration(), serverTaskDataBean.getCommentText());
                break;
            case TaskTypeConfig.TIKTOK_TASK_SINGLE_CHAT_TO_USER:
                //主动私聊
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                showLogAndTsPrint("主动私聊任务>>开始");
                chatWithOtherNow();
                break;
            case TaskTypeConfig.TIKTOK_TASK_CHANGE_PERSONAL_INFO:
                showLogAndTsPrint("修改用户资料任务>>开始");
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                //修改个人资料
                tickTokTaskDealTools.changePersonalInfo(serverTaskDataBean.getNickName(), serverTaskDataBean.getIntroduction(), serverTaskDataBean.getAvatar());
                break;
            case TaskTypeConfig.TIKTOK_TASK_AUTO_PUBLISH_WORKS:
                showLogAndTsPrint("发布作品任务>>开始");
                if (!checkIsCurrentUserSameAsServerUser()) {
                    return;
                }
                if (MyUtils.isEmpty(serverTaskDataBean.getFileDirName())) {
                    onTaskErr("文件夹名称不能为空");
                    return;
                }
                //自动发布作品
                tickTokTaskDealTools.publishWorks(serverTaskDataBean.getFileDirName(), serverTaskDataBean.getPublishTitle());
                break;
            case TaskTypeConfig.TIKTOK_TASK_AUTO_REPLAY_BE_ATTENTION:
                showLogAndTsPrint("被关注自动回复任务>>开始");
                attentionAndReplayTask();
                break;
            case TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO:
                if(MyUtils.isEmpty(serverTaskDataBean.getId())){
                    showLogAndTsPrint("服务端同步数据任务>>开始");
                }else {
                    showLogAndTsPrint("定时更新数据任务>>开始");
                }
                autoUpdateDataTask();
                break;
            case TaskTypeConfig.TEST:
                //做测试用的
                test();
                break;
            case TaskTypeConfig.TIKTOK_TASK_AUTO_REGISTER:
                //自动注册账号
                autoRegister();
                break;
            case TaskTypeConfig.TIKTOK_TASK_AUTO_LOGIN:
                //自动登录账号
                showLogAndTsPrint("准备登录>>"+serverTaskDataBean.getAccountId());
                int time=0;
                while (time<4&&!Constants.tiktokPackageName.equals(AccessibilityTool.getInstance().getCurrentPagePackageName(service))){
                    Thread.sleep(500);
                    time++;
                }
                autoLogin();
                break;
        }
    }

    private void autoLogin() throws InterruptedException {
        //不在选择tag页面,判断是否在首页,防止有弹框
      tickTokTaskDealTools.closeDialogAndSwipe();
      if (tickTokTaskDealTools.isFirstInTikTokAndInSelectTagAc()) {
            //在选择tag页面
            if (tickTokTaskDealTools.isEnterInStartLookNextPage()) {
                //成功进入了tiktok主页面了
                if (tickTokTaskDealTools.checkIsInPersonalPage()) {
                    boolean isEnterInLoginAc = enterInLoginAcFromPersonalPage();
                    if (isEnterInLoginAc) {
                        changeLoginWayAndLogin();
                    } else {
                        onTaskErr("无法进入选择登录页面");
                    }
                } else {
                    //先关闭某些碍事的弹框
                    AccessibilityNodeInfo node = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
                    if (node != null) {
                        tickTokTaskDealTools.clickXy(node);
                        Thread.sleep(3000);
                        boolean isEnterInLoginAc = enterInLoginAcFromPersonalPage();
                        if (isEnterInLoginAc) {
                            changeLoginWayAndLogin();
                        } else {
                            onTaskErr("无法进入选择登录页面");
                        }
                    } else {
                        onTaskErr("未找到底部主页按钮");
                    }
                }
            } else {
                Thread.sleep(3000);
                onTaskErr("进入tiktok主页面失败了");
            }
        }else {
          //判断是否在选择生日页面
          if (tickTokTaskDealTools.isInBirthDaySelectOnlyResult()) {
              //在选择生日页面
              AccessibilityNodeInfo toLoginBtNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.birthday_select_to_login_bt);
              if(toLoginBtNode!=null){
                  tickTokTaskDealTools.clickXy(toLoginBtNode);
                  Thread.sleep(3000);
                  List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                  AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                  if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                      if (itemNodes.size()==4) {
                          tickTokTaskDealTools.clickXy(itemNodes.get(0));
                          showLogAndTsPrint("进入登录页面");
                          Thread.sleep(3000);
                          changeLoginWayAndLogin();
                      } else {
                          if(itemNodes.size()==3) {
                              tickTokTaskDealTools.clickXy(bottomChangeNode);
                              showLogAndTsPrint("切换到登录方式选择弹框");
                              Thread.sleep(4000);
                              itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                              if (tickTokTaskDealTools.isNodeExist(itemNodes)&&itemNodes.get(0).isVisibleToUser()) {
                                  tickTokTaskDealTools.clickXy(itemNodes.get(0));
                                  showLogAndTsPrint("进入登录页面");
                                  Thread.sleep(4000);
                              } else {
                                  onTaskErr("无法进入登录页面");
                              }
                          }else{
                              onTaskErr("无法进入登录页面");
                          }
                      }
                  }else{
                      onTaskErr("无法进入登录页面");
                  }
              }else{
                  onTaskErr("无法进入登录页面");
              }
              return;
          }

          if (tickTokTaskDealTools.checkIsInPersonalPage()) {
              //当前在个人主页
              boolean isEnterInLoginAc = enterInLoginAcFromPersonalPage();
              if (isEnterInLoginAc) {
                  changeLoginWayAndLogin();
              } else {
                  onTaskErr("无法进入选择登录页面");
              }
          } else {
              //没有在个人主页
              AccessibilityNodeInfo node = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
              if (node != null) {
                  tickTokTaskDealTools.clickXy(node);
                  Thread.sleep(4000);
                  boolean isEnterInLoginAc = enterInLoginAcFromPersonalPage();
                  if (isEnterInLoginAc) {
                      changeLoginWayAndLogin();
                  } else {
                      onTaskErr("无法进入选择登录页面");
                  }
              } else {
                  if(!tickTokTaskDealTools.checkCurrentPageIsMainPage()) {
                      tickTokTaskDealTools.backOnce();
                      Thread.sleep(3000);
                      changeTaskStatusToStart();
                  }else{
                      Thread.sleep(2000);
                      autoLogin();
                  }
              }
          }
        }
    }


    /**
     * 切换标签到邮箱登录并开始登录
     */
    SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
    private void changeLoginWayAndLogin() throws InterruptedException {
        String email=serverTaskDataBean.getAccountId();
        AccessibilityNodeInfo cancelDialog = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_phone_dialog_choose_tel);
        if(cancelDialog!=null){
            showLogAndTsPrint("关闭弹框");
            tickTokTaskDealTools.clickXy(cancelDialog);
            Thread.sleep(3000);
        }
        List<AccessibilityNodeInfo> tabNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
        if(tickTokTaskDealTools.isNodeExist(tabNodes)&&tabNodes.size()>=2){
            showLogAndTsPrint("切换到邮箱登录方式");
            tickTokTaskDealTools.clickXy(tabNodes.get(1));
            Thread.sleep(2000);
            AccessibilityNodeInfo etNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_phone_or_email_edit_tel_node);
            if(etNode!=null) {
                tickTokTaskDealTools.setNodeText(etNode,email);
                Thread.sleep(2400);
                AccessibilityNodeInfo loginBtNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.loginNextBtId);
                if(loginBtNode!=null) {
                    requestEmailTime=System.currentTimeMillis();
                    tickTokTaskDealTools.clickXy(loginBtNode);
                    showLogAndTsPrint("点击登录");
                    Thread.sleep(2000);
//                    Thread.sleep(10000);
                    List<AccessibilityNodeInfo> nodes = tickTokTaskDealTools.findNodesByText("查看你的邮箱");
                    boolean isNotEnterInNext=!tickTokTaskDealTools.isNodeExist(nodes)||tickTokTaskDealTools.isNodeExist(tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId))&&tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId).size()>=2;
                    long time=0;
                    while (time<10&&isNotEnterInNext){
                        nodes = tickTokTaskDealTools.findNodesByText("查看你的邮箱");
                        isNotEnterInNext=!tickTokTaskDealTools.isNodeExist(nodes)||tickTokTaskDealTools.isNodeExist(tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId))&&tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId).size()>=2;
                        time++;
                        Thread.sleep(1000);
                    }
                    tabNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
                    if(tickTokTaskDealTools.isNodeExist(tabNodes)&&tabNodes.size()>=2){
                        onTaskErr("无法进入验证码输入页");
                        return;
                    }
                    AccessibilityNodeInfo toManyNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.request_to_many_text_id);
                    if(toManyNode!=null){
                        onTaskErr("账号被风控，登录失败");
                        return;
                    }
                    AccessibilityNodeInfo verifyCodeInputEtNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_input_phone_code_edit_id);
                    if(verifyCodeInputEtNode!=null){
                        TsUtils.showTips("等待接收邮箱验证码:"+dateFormat.format(requestEmailTime));
                        currentEmailCode="";
                        WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(createGetEmailCodeMsgDataBean(email,requestEmailTime)));
                        loopToGetAndInputVerifyCode(0,email);
                    }else{
                        onTaskErr("无法找到验证码输入框");
                    }
                }else{
                    onTaskErr("无法找到登录按钮");
                }

            }else{
                onTaskErr("无法找到邮箱输入框");
            }

        }else{
            cancelDialog = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_phone_dialog_choose_tel);
            if(cancelDialog!=null){
                showLogAndTsPrint("关闭弹框");
                tickTokTaskDealTools.clickXy(cancelDialog);
                Thread.sleep(3000);
                changeLoginWayAndLogin();
                return;
            }
            onTaskErr("无法进入邮箱登录页");
        }
    }


    public void setCurrentEmailCode(String currentEmailCode) {
        String email=serverTaskDataBean.getAccountId();
        if(MyUtils.isEmpty(currentEmailCode)){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(System.currentTimeMillis()-requestEmailTime<60*1000){
                        WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(createGetEmailCodeMsgDataBean(email,requestEmailTime)));
                    }
                }
            },2000);
        }
        this.currentEmailCode = currentEmailCode;
    }

    private void loopToGetAndInputVerifyCode(int retryTimes, String email) throws InterruptedException {
        while (MyUtils.isEmpty(currentEmailCode)){
            try {
                Thread.sleep(3000);
                if(System.currentTimeMillis()-requestEmailTime>=70*1000){
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(MyUtils.isEmpty(currentEmailCode)){
            if(System.currentTimeMillis()-requestEmailTime>=70*1000){
                showLogAndTsPrint("邮箱验证码获取超时，准备重试一次");
                Thread.sleep(2000);
                AccessibilityNodeInfo reGetVerifyCodeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.login_re_get_verifyCode);
                if(reGetVerifyCodeNode!=null) {
                    retryTimes++;
                    currentEmailCode="";
                    if(retryTimes>=2){
                        onTaskErr("邮箱验证码获取失败");
                        return;
                    }
                    tickTokTaskDealTools.clickXy(reGetVerifyCodeNode);
                    requestEmailTime=System.currentTimeMillis();
                    WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(createGetEmailCodeMsgDataBean(email,requestEmailTime)));
                    Thread.sleep(3000);
                    TsUtils.showTips("等待接收邮箱验证码:"+dateFormat.format(requestEmailTime));
                    loopToGetAndInputVerifyCode(retryTimes,email);
                }else{
                    onTaskErr("无法找到重新获取验证码按钮");
                }
            }else{
                onTaskErr("接口返回验证码为空");
            }
        }else {
            AccessibilityNodeInfo verifyCodeInputEtNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_input_phone_code_edit_id);
            if (verifyCodeInputEtNode != null) {
                tickTokTaskDealTools.setNodeText(verifyCodeInputEtNode, currentEmailCode);
                TsUtils.showTips("输入验证码完成");
//                Thread.sleep(10000);
                int time=0;
                boolean isNotEnterInNext=tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_input_phone_code_edit_id)!=null;
                while (time<10&&isNotEnterInNext){
                    Thread.sleep(2000);
                    isNotEnterInNext=tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_input_phone_code_edit_id)!=null;
                    time++;
                }
                verifyCodeInputEtNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_input_phone_code_edit_id);
                if(verifyCodeInputEtNode!=null){
                    onTaskErr("验证码输入有误或未获取成功");
                    return;
                }
                List<AccessibilityNodeInfo> nodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_tips);
                List<AccessibilityNodeInfo> pwdVerifyNodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_pwd_verify);
                time=0;
                isNotEnterInNext=!tickTokTaskDealTools.isNodeExist(nodes)&&!tickTokTaskDealTools.isNodeExist(pwdVerifyNodes);
                while (time<10&&isNotEnterInNext){
                    Thread.sleep(1000);
                    nodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_tips);
                    pwdVerifyNodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_pwd_verify);
                    isNotEnterInNext=!tickTokTaskDealTools.isNodeExist(nodes)&&!tickTokTaskDealTools.isNodeExist(pwdVerifyNodes);
                    time++;
                }
                checkAndSendMessageToServer();
                TsUtils.showTips("登录成功");
                tickTokTaskDealTools.getCurrentAccountAndSendToServer(0,email);
            }else{
                onTaskErr("无法找到验证码输入框");
            }
        }
    }

    public void checkAndSendMessageToServer() throws InterruptedException {
        List<AccessibilityNodeInfo> nodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_tips);
        List<AccessibilityNodeInfo> pwdVerifyNodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_pwd_verify);
        if(tickTokTaskDealTools.isNodeExist(nodes)&&tickTokTaskDealTools.isNodeExist(pwdVerifyNodes)){
            showLogAndTsPrint("出现身份认证页面");
            tickTokTaskDealTools.clickXy(pwdVerifyNodes.get(0));
            Thread.sleep(2000);
            showLogAndTsPrint("点击进行密码认证");
            List<AccessibilityNodeInfo> toNextNodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_pwd_to_next);
            if(tickTokTaskDealTools.isNodeExist(toNextNodes)){
                tickTokTaskDealTools.clickXy(toNextNodes.get(0));
                Thread.sleep(2000);
                List<AccessibilityNodeInfo> etNodes = tickTokTaskDealTools.findNodeInfoByClassName(null,FindIdResouresConfig.login_verify_page_pwd_input_et);
                if(tickTokTaskDealTools.isNodeExist(etNodes)){
                    String pwd = serverTaskDataBean.getPassword();
                    tickTokTaskDealTools.setNodeText(etNodes.get(0),pwd);
                    toNextNodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_pwd_to_next);
                    if(tickTokTaskDealTools.isNodeExist(toNextNodes)) {
                        Thread.sleep(2000);
                        tickTokTaskDealTools.clickXy(toNextNodes.get(0));
                        Thread.sleep(5000);
                        etNodes = tickTokTaskDealTools.findNodeInfoByClassName(null,FindIdResouresConfig.login_verify_page_pwd_input_et);
                        toNextNodes = tickTokTaskDealTools.findNodesByText(FindIdResouresConfig.login_verify_page_pwd_to_next);
                        if(tickTokTaskDealTools.isNodeExist(etNodes)&&tickTokTaskDealTools.isNodeExist(toNextNodes)){
                            onTaskErr("密码认证失败");
                        }
                    }else{
                        onTaskErr("无法找到下一步按钮");
                    }
                }else{
                    onTaskErr("无法找到密码输入框");
                }
            }else{
                onTaskErr("身份认证失败");
            }
        }
    }


    private MsgTaskBean createGetEmailCodeMsgDataBean(String email,long date) {
        MsgTaskBean msgTaskBean=new MsgTaskBean();
        msgTaskBean.setTaskType(currentTaskType);
        msgTaskBean.setType(14);
        msgTaskBean.setCode(1003);
        msgTaskBean.setToken(SPUtils.getInstance().getString("token"));
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("email",email);
        jsonObject.addProperty("appType",0);
        jsonObject.addProperty("date",date);
        ServerInnerDataBean serverInnerDataBean=new ServerInnerDataBean();
        serverInnerDataBean.setJson(GsonUtils.toJson(jsonObject));
        msgTaskBean.setData(serverInnerDataBean);
        return msgTaskBean;
    }

    private void autoRegister() throws InterruptedException {
        if(!isResetTikTok){
            MsgTaskManger.dealWithAutoRegisterLauncher(this);
            return;
        }
        showLogAndTsPrint("自动注册任务>>开始");
        Thread.sleep(3000);
        tickTokTaskDealTools.closeDialogAndSwipe();
        if (tickTokTaskDealTools.isInBirthDaySelectPageAndScrollYear()) {
            //已经在注册选择生日的页面了
            inputAccountAndRegister();
        } else if (tickTokTaskDealTools.isFirstInTikTokAndInSelectTagAc()) {
            //没有在注册选择生日页面
            if (tickTokTaskDealTools.isEnterInStartLookNextPage()) {
                //成功进入了tiktok主页面了
                if (tickTokTaskDealTools.checkIsInPersonalPage()) {
                    boolean isEnterInBirthDayAc = enterInBirthDaySelectAc();
                    if (isEnterInBirthDayAc) {
                        if (tickTokTaskDealTools.isInBirthDaySelectPageAndScrollYear()) {
                            inputAccountAndRegister();
                        }else{
                            AccessibilityNodeInfo cancelDialog = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_phone_dialog_choose_tel);
                            if(cancelDialog!=null){
                                showLogAndTsPrint("关闭弹框");
                                tickTokTaskDealTools.clickXy(cancelDialog);
                                Thread.sleep(3000);
                            }
                            List<AccessibilityNodeInfo> tabNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
                            if(tickTokTaskDealTools.isNodeExist(tabNodes)&&tabNodes.size()>=2){
                                inputAccountAndRegister();
                            }else {
                                autoRegister();
                            }
                        }
                    } else {
                        onTaskErr("无法进入选择生日页面");
                    }
                } else {
                    AccessibilityNodeInfo node = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
                    if (node != null) {
                        tickTokTaskDealTools.clickXy(node);
                        Thread.sleep(3000);
                        boolean isEnterInBirthDayAc = enterInBirthDaySelectAc();
                        if (isEnterInBirthDayAc) {
                            if (tickTokTaskDealTools.isInBirthDaySelectPageAndScrollYear()) {
                                inputAccountAndRegister();
                            }else{
                                AccessibilityNodeInfo cancelDialog = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_phone_dialog_choose_tel);
                                if(cancelDialog!=null){
                                    showLogAndTsPrint("关闭弹框");
                                    tickTokTaskDealTools.clickXy(cancelDialog);
                                    Thread.sleep(3000);
                                }
                                List<AccessibilityNodeInfo> tabNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
                                if(tickTokTaskDealTools.isNodeExist(tabNodes)&&tabNodes.size()>=2){
                                    inputAccountAndRegister();
                                }else {
                                    autoRegister();
                                }
                            }
                        } else {
                            onTaskErr("无法进入选择生日页面");
                        }
                    } else {
                        onTaskErr("未找到底部主页按钮");
                    }
                }
            } else {
                Thread.sleep(3000);
                onTaskErr("进入tiktok主页面失败了");
            }
        }else {
            if (tickTokTaskDealTools.checkIsInPersonalPage()) {
                boolean isEnterInBirthDayAc = enterInBirthDaySelectAc();
                if (isEnterInBirthDayAc) {
                    if (tickTokTaskDealTools.isInBirthDaySelectPageAndScrollYear()) {
                        inputAccountAndRegister();
                    }else{
                        AccessibilityNodeInfo cancelDialog = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_phone_dialog_choose_tel);
                        if(cancelDialog!=null){
                            showLogAndTsPrint("关闭弹框");
                            tickTokTaskDealTools.clickXy(cancelDialog);
                            Thread.sleep(3000);
                        }
                        List<AccessibilityNodeInfo> tabNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
                        if(tickTokTaskDealTools.isNodeExist(tabNodes)&&tabNodes.size()>=2){
                            inputAccountAndRegister();
                        }else {
                            autoRegister();
                        }
                    }
                } else {
                    onTaskErr("无法进入选择生日页面");
                }
            } else {
                AccessibilityNodeInfo node = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.personalBottomBtId);
                if (node != null) {
                    tickTokTaskDealTools.clickXy(node);
                    Thread.sleep(4000);
                    boolean isEnterInBirthDayAc = enterInBirthDaySelectAc();
                    if (isEnterInBirthDayAc) {
                        if (tickTokTaskDealTools.isInBirthDaySelectPageAndScrollYear()) {
                            inputAccountAndRegister();
                        }else{
                            AccessibilityNodeInfo cancelDialog = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_phone_dialog_choose_tel);
                            if(cancelDialog!=null){
                                showLogAndTsPrint("关闭弹框");
                                tickTokTaskDealTools.clickXy(cancelDialog);
                                Thread.sleep(3000);
                            }
                            List<AccessibilityNodeInfo> tabNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_tab_phone_email_register_NodeId);
                            if(tickTokTaskDealTools.isNodeExist(tabNodes)&&tabNodes.size()>=2){
                                inputAccountAndRegister();
                            }else {
                                autoRegister();
                            }
                        }
                    } else {
                        onTaskErr("无法进入选择生日页面");
                    }
                } else {
                    isResetTikTok=false;
                    TaskManager.isRegisterTaskDoing=false;
                    onTaskErr("无法找到节点");
                }
            }
        }
    }

    private void inputAccountAndRegister() throws InterruptedException {
        if (!tickTokTaskDealTools.isInRegisterSelectWayToReg(1, serverTaskDataBean.getAccountId(), "+86",serverTaskDataBean.getPassword(),"aaaw"+new Random(15232))) {
            List<AccessibilityNodeInfo> closeAgreeDialogBt = tickTokTaskDealTools.findNodesByText("同意并继续");
            if(tickTokTaskDealTools.isNodeExist(closeAgreeDialogBt)){
                tickTokTaskDealTools.clickXy(closeAgreeDialogBt.get(0));
                tickTokTaskDealTools.tikTokTask.showLogAndTsPrint("同意并继续");
                Thread.sleep(3000);
                autoRegister();
            }else{
                List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                    Thread.sleep(1000);
                    autoRegister();
                }else {
                    onTaskErr("无法进入注册页面");
                }
            }
        }
    }


    /**
     * 从个人主页页面进入登录页面
     */
    private boolean enterInLoginAcFromPersonalPage() throws InterruptedException {
        boolean isEnterInLoginAc = false;
        AccessibilityNodeInfo node = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.personalUnLoginStatusCenterLoginBtId);
        if (node != null) {
            tickTokTaskDealTools.clickXy(node);
            showLogAndTsPrint("点击登录按钮弹出登录弹框");
            Thread.sleep(3000);
            List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
            AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
            if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                if (itemNodes.size()==4) {
                    tickTokTaskDealTools.clickXy(itemNodes.get(0));
                    showLogAndTsPrint("进入登录页面");
                    Thread.sleep(3000);
                    isEnterInLoginAc = true;
                } else {
                    if(itemNodes.size()==3) {
                        tickTokTaskDealTools.clickXy(bottomChangeNode);
                        showLogAndTsPrint("切换到登录方式选择弹框");
                        Thread.sleep(4000);
                        itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                        if (tickTokTaskDealTools.isNodeExist(itemNodes)&&itemNodes.get(0).isVisibleToUser()) {
                            tickTokTaskDealTools.clickXy(itemNodes.get(0));
                            showLogAndTsPrint("进入登录页面");
                            Thread.sleep(4000);
                            isEnterInLoginAc = true;
                        } else {
                            onTaskErr("无法进入登录页面");
                        }
                    }else{
                        onTaskErr("无法进入登录页面");
                    }
                }
            }else{
                onTaskErr("无法进入登录页面");
            }
        } else {
            AccessibilityNodeInfo changeBtId = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.changeAccountBtId);
            if (changeBtId != null) {
                if(Constants.isServiceApplication) {
                    AccessibilityTool.getInstance().clickScreen(service, 440, 100);
                    Thread.sleep(2000);
                    List<AccessibilityNodeInfo> accountsNode = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.accountListTextId);
                    if(!tickTokTaskDealTools.isNodeExist(accountsNode)){
                        tickTokTaskDealTools.clickXy(changeBtId);
                        Thread.sleep(2000);
                    }
                }else{
                    tickTokTaskDealTools.clickXy(changeBtId);
                    Thread.sleep(3000);
                }
                List<AccessibilityNodeInfo> accountsNode = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.accountListTextId);
                if (tickTokTaskDealTools.isNodeExist(accountsNode)) {
                    AccessibilityNodeInfo addAccountBt = accountsNode.get(accountsNode.size() - 1);
                    if (addAccountBt != null) {
                        tickTokTaskDealTools.clickXy(addAccountBt);
                        showLogAndTsPrint("点击登录按钮弹出登录弹框");
                        Thread.sleep(3000);
                        List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                        AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                        if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                            if (itemNodes.size()==4) {
                                tickTokTaskDealTools.clickXy(itemNodes.get(0));
                                showLogAndTsPrint("进入登录页面");
                                Thread.sleep(3000);
                                isEnterInLoginAc = true;
                            } else {
                                if(itemNodes.size()==3) {
                                    tickTokTaskDealTools.clickXy(bottomChangeNode);
                                    showLogAndTsPrint("切换到登录方式选择弹框");
                                    Thread.sleep(4000);
                                    itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                                    if (tickTokTaskDealTools.isNodeExist(itemNodes)&&itemNodes.get(0).isVisibleToUser()) {
                                        tickTokTaskDealTools.clickXy(itemNodes.get(0));
                                        showLogAndTsPrint("进入登录页面");
                                        Thread.sleep(4000);
                                        isEnterInLoginAc = true;
                                    } else {
                                        onTaskErr("无法进入登录页面");
                                    }
                                }else{
                                    onTaskErr("无法进入登录页面");
                                }
                            }
                        }else{
                            onTaskErr("无法进入登录页面");
                        }
                    }
                }
            }else{
                List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                    if (itemNodes.size()==4) {
                        tickTokTaskDealTools.clickXy(itemNodes.get(0));
                        showLogAndTsPrint("进入登录页面");
                        Thread.sleep(3000);
                        isEnterInLoginAc = true;
                    } else {
                        if(itemNodes.size()==3) {
                            tickTokTaskDealTools.clickXy(bottomChangeNode);
                            showLogAndTsPrint("切换到登录方式选择弹框");
                            Thread.sleep(4000);
                            itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                            if (tickTokTaskDealTools.isNodeExist(itemNodes)&&itemNodes.get(0).isVisibleToUser()) {
                                tickTokTaskDealTools.clickXy(itemNodes.get(0));
                                showLogAndTsPrint("进入登录页面");
                                Thread.sleep(4000);
                                isEnterInLoginAc = true;
                            } else {
                                onTaskErr("无法进入登录页面");
                            }
                        }else{
                            onTaskErr("无法进入登录页面");
                        }
                    }
                }else{
                    onTaskErr("无法进入登录页面");
                }
            }
        }
        return isEnterInLoginAc;
    }






    /**
     * 从个人主页页面进入注册页面
     */
    private boolean enterInBirthDaySelectAc() throws InterruptedException {
        boolean isEnterInRegMainAc = false;
        AccessibilityNodeInfo node = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.personalUnLoginStatusCenterLoginBtId);
        if (node != null) {
            tickTokTaskDealTools.clickXy(node);
            showLogAndTsPrint("点击登录按钮弹出登录弹框");
            Thread.sleep(3000);
            List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
            AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
            if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                if (itemNodes.size()==3) {
                    tickTokTaskDealTools.clickXy(itemNodes.get(0));
                    showLogAndTsPrint("进入注册页面");
                    Thread.sleep(3000);
                    isEnterInRegMainAc = true;
                } else {
                    if(itemNodes.size()==4) {
                        tickTokTaskDealTools.clickXy(bottomChangeNode);
                        showLogAndTsPrint("切换到注册方式选择弹框");
                        Thread.sleep(4000);
                        itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                        if (tickTokTaskDealTools.isNodeExist(itemNodes)&&itemNodes.get(0).isVisibleToUser()) {
                            tickTokTaskDealTools.clickXy(itemNodes.get(0));
                            showLogAndTsPrint("进入注册页面");
                            Thread.sleep(4000);
                            isEnterInRegMainAc = true;
                        } else {
                            onTaskErr("无法进入注册页面");
                        }
                    }else{
                        onTaskErr("无法进入注册页面");
                    }
                }
            }else{
                onTaskErr("无法进入注册页面");
            }
        } else {
            AccessibilityNodeInfo changeBtId = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.changeAccountBtId);
            if (changeBtId != null) {
                if(Constants.isServiceApplication) {
                    AccessibilityTool.getInstance().clickScreen(service, 440, 100);
                    Thread.sleep(2000);
                    List<AccessibilityNodeInfo> accountsNode = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.accountListTextId);
                    if(!tickTokTaskDealTools.isNodeExist(accountsNode)){
                        tickTokTaskDealTools.clickXy(changeBtId);
                        Thread.sleep(2000);
                    }
                }else{
                    tickTokTaskDealTools.clickXy(changeBtId);
                    Thread.sleep(3000);
                }
                List<AccessibilityNodeInfo> accountsNode = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.accountListTextId);
                if (tickTokTaskDealTools.isNodeExist(accountsNode)) {
                    AccessibilityNodeInfo addAccountBt = accountsNode.get(accountsNode.size() - 1);
                    if (addAccountBt != null) {
                        tickTokTaskDealTools.clickXy(addAccountBt);
                        showLogAndTsPrint("点击登录按钮弹出登录弹框");
                        Thread.sleep(3000);
                        List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                        AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                        if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                            if (itemNodes.size()==3) {
                                tickTokTaskDealTools.clickXy(itemNodes.get(0));
                                showLogAndTsPrint("进入注册页面");
                                Thread.sleep(3000);
                                isEnterInRegMainAc = true;
                            } else {
                                if(itemNodes.size()==4) {
                                    tickTokTaskDealTools.clickXy(bottomChangeNode);
                                    showLogAndTsPrint("切换到注册方式选择弹框");
                                    Thread.sleep(4000);
                                    itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                                    if (tickTokTaskDealTools.isNodeExist(itemNodes)&&itemNodes.get(0).isVisibleToUser()) {
                                        tickTokTaskDealTools.clickXy(itemNodes.get(0));
                                        showLogAndTsPrint("进入注册页面");
                                        Thread.sleep(4000);
                                        isEnterInRegMainAc = true;
                                    } else {
                                        onTaskErr("无法进入注册页面");
                                    }
                                }else{
                                    onTaskErr("无法进入注册页面");
                                }
                            }
                        }else{
                            onTaskErr("无法进入注册页面");
                        }
                    }
                }
            }else{
                List<AccessibilityNodeInfo> itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                AccessibilityNodeInfo bottomChangeNode = tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.register_dialog_bottom_change_register_id);
                if (tickTokTaskDealTools.isNodeExist(itemNodes) && bottomChangeNode != null) {
                    if (itemNodes.size()==3) {
                        tickTokTaskDealTools.clickXy(itemNodes.get(0));
                        showLogAndTsPrint("进入注册页面");
                        Thread.sleep(3000);
                        isEnterInRegMainAc = true;
                    } else {
                        if(itemNodes.size()==4) {
                            tickTokTaskDealTools.clickXy(bottomChangeNode);
                            showLogAndTsPrint("切换到注册方式选择弹框");
                            Thread.sleep(4000);
                            itemNodes = tickTokTaskDealTools.findNodesById(FindIdResouresConfig.register_dialog_bottom_item_node_id);
                            if (tickTokTaskDealTools.isNodeExist(itemNodes)&&itemNodes.get(0).isVisibleToUser()) {
                                tickTokTaskDealTools.clickXy(itemNodes.get(0));
                                showLogAndTsPrint("进入注册页面");
                                Thread.sleep(4000);
                                isEnterInRegMainAc = true;
                            } else {
                                onTaskErr("无法进入注册页面");
                            }
                        }else{
                            onTaskErr("无法进入注册页面");
                        }
                    }
                }else{
                    List<AccessibilityNodeInfo> nodes = AccessibilityTool.getInstance().findNodesByText(null, null, service, "上滑查看更多视频");
                    if(tickTokTaskDealTools.isNodeExist(nodes)){
                        tickTokTaskDealTools.swipeYearScrollBarToBottom(1);
                        Thread.sleep(2000);
                        return false;
                    }
                    AccessibilityNodeInfo swipeNodeImageNode =tickTokTaskDealTools.findNodeFirstById(FindIdResouresConfig.swipe_center_tips_node_id);
                    if(swipeNodeImageNode!=null){
                        tickTokTaskDealTools.swipeYearScrollBarToBottom(1);
                        Thread.sleep(2000);
                        return false;
                    }
                    onTaskErr("无法进入注册页面777");
                }
            }
        }
        return isEnterInRegMainAc;
    }


    /**
     * 主动私信用户
     */
    private void chatWithOtherNow() throws InterruptedException {
        String currentNeedDealUserName = serverTaskDataBean.getFollowAccount();
        if (MyUtils.isEmpty(serverTaskDataBean.getMsgList())) {
            onTaskErr("需要私信的用户名不能为空");
            return;
        }
        int rIndex = new Random().nextInt(serverTaskDataBean.getMsgList().size());
        String chatContent = serverTaskDataBean.getMsgList().get(rIndex);
        //私信单个用户
        boolean isChatSuccess = tickTokTaskDealTools.chatWithSingleUser(currentNeedDealUserName, chatContent);
        if (isChatSuccess) {
            onTaskFinish();
        } else {
            onTaskErr("私信任务执行失败");
        }
        LogUtils.i("本次私聊用户：" + currentNeedDealUserName + "/话术：" + chatContent + "——>" + (isChatSuccess ? "发送成功" : "发送失败"));
    }

    private void jumpToNormalWebAc() throws InterruptedException {
        LogUtils.e("不在app的页面，切换回app页面");
        AppUtils.Companion.launchApp(BaseApp.app.getApplicationContext(), BaseApp.app.getPackageName());
        Thread.sleep(3000);
        Intent intents = new Intent(BaseApp.app, NormalWebActivity.class);
        intents.putExtra("url", serverTaskDataBean.getVideoLink());
        intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        BaseApp.app.getApplicationContext().startActivity(intents);
    }


    /**
     * 自动更新数据任务
     */
    private void autoUpdateDataTask() throws InterruptedException {
        //定时任务---更新用户信息以及本机状态
        tickTokTaskDealTools.getUserInfo(new TickTokTaskDealTools.OnUserInfoGetListener() {
            @Override
            public void onUserInfoGet(UserInfo userInfo) throws InterruptedException {
                createCurrentUpdateInfo(userInfo,2,true);
                sendMsgToServer();
                if(userInfo!=null) {
                    if (isBeAttentionAutoReplayOpen()) {
                        LogUtils.v("切换任务为被关注后主动私信");
                        createBeAttentionReplayTask();
                    } else {
                        Thread.sleep(2000);
                        onTaskFinish();
                    }
                }else{
                    onTaskFinish();
                }
            }
        }, null);
    }


    /**
     * 被关注自动回复任务
     */
    public void attentionAndReplayTask() throws InterruptedException {
        if (MyUtils.isEmpty(serverTaskDataBean.getAccountWithUserName()) && TaskManager.getInstance().currentTiktokUserInfo != null) {
            serverTaskDataBean.setAccountWithUserName(TaskManager.getInstance().currentTiktokUserInfo.getAccount());
        }
        if (!checkIsCurrentUserSameAsServerUser()) {
            return;
        }
        if (TaskManager.getInstance().currentTiktokUserInfo == null || MyUtils.isEmpty(serverTaskDataBean.getBeAttentionReplayBeans())) {
            LogUtils.e("被关注后自动私信的数据为空或用户信息为空，关闭此任务");
            onTaskFinish();
            return;
        }
        int nowAccountIndex = -1;
        for (int i = 0; i < serverTaskDataBean.getBeAttentionReplayBeans().size(); i++) {
            if (serverTaskDataBean.getBeAttentionReplayBeans().get(i).getAccount().equals(TaskManager.getInstance().currentTiktokUserInfo.getAccount())) {
                nowAccountIndex = i;
                break;
            }
        }
        if (nowAccountIndex == -1) {
            LogUtils.e("被关注后私信的列表与当前登录的用户全都无法匹配，不执行该任务");
            onTaskErr("需执行的账号不在本地登录列表中");
            return;
        }
        ChatMsgList attentionReplayBean = serverTaskDataBean.getBeAttentionReplayBeans().get(nowAccountIndex);
        if (MyUtils.isEmpty(attentionReplayBean.getPrivateMsgList())) {
            LogUtils.e("此账号自动私信任务已被关闭");
            hasBeAttentionAccount.add(attentionReplayBean);
            beAttentionAutoReplayAccountIndex++;
            onTaskFinish();
            return;
        }
        //被关注自动私信
        tickTokTaskDealTools.autoReplayWhenBeAttention(attentionReplayBean, new TickTokTaskDealTools.OnAttentionCommentOverListener() {
            @Override
            public void onFinish(boolean isSuccess) throws InterruptedException {
                hasBeAttentionAccount.add(attentionReplayBean);
                beAttentionAutoReplayAccountIndex++;
                LogUtils.e("已完成账号切换个数：" + beAttentionAutoReplayAccountIndex + "个");
                if (!isSuccess) {
                    onTaskFinish();
                    return;
                }
                if (isBeAttentionAutoReplayOpen()) {
                    if (!MyUtils.isEmpty(serverTaskDataBean.getBeAttentionReplayBeans())) {
                        if (beAttentionAutoReplayAccountIndex >= serverTaskDataBean.getBeAttentionReplayBeans().size()) {
                            LogUtils.e("被关注私信的所有账号都已经完成：共计-" + beAttentionAutoReplayAccountIndex + "个");
                            onTaskFinish();
                        } else {
                            int nowAccountIndex = -1;
                            for (int i = 0; i < serverTaskDataBean.getBeAttentionReplayBeans().size(); i++) {
                                ChatMsgList serverData = serverTaskDataBean.getBeAttentionReplayBeans().get(i);
                                for (int j = 0; j < hasBeAttentionAccount.size(); j++) {
                                    if (!serverData.getAccount().equals(hasBeAttentionAccount.get(j).getAccount())) {
                                        nowAccountIndex = i;
                                        break;
                                    }
                                }
                            }
                            if (nowAccountIndex > -1) {
                                String newUserName = serverTaskDataBean.getBeAttentionReplayBeans().get(nowAccountIndex).getAccount();
                                LogUtils.e("新的用户名切换为：" + newUserName);
                                serverTaskDataBean.setAccountWithUserName(newUserName);
                                checkIsCurrentUserSameAsServerUser();
                            } else {
                                onTaskErr("需执行的账号切换失败");
                            }
                        }
                    } else {
                        onTaskFinish();
                    }
                } else {
                    onTaskFinish();
                }
            }
        });
    }


    public boolean isBeAttentionAutoReplayOpen() {
        if (serverTaskDataBean == null) {
            return false;
        }
        if (MyUtils.isEmpty(serverTaskDataBean.getBeAttentionReplayBeans())) {
            return false;
        }
        return true;
    }


    private void createBeAttentionReplayTask() {
        beAttentionAutoReplayAccountIndex = 0;
        hasBeAttentionAccount.clear();
        ServerTaskDataBean serverTaskDataBean = this.serverTaskDataBean;
        serverTaskDataBean.setTaskType(TaskTypeConfig.TIKTOK_TASK_AUTO_REPLAY_BE_ATTENTION);
        TaskManager.getInstance().createTikTokTask(serverTaskDataBean);
        String pkgName = AccessibilityTool.getInstance().getCurrentPagePackageName(service);
        if (!Constants.tiktokPackageName.equals(pkgName)) {
            LogUtils.i("当前包名跟tiktok不一致，打开tiktok");
            TaskManager.getInstance().onOpenTaskApp(TaskManager.getInstance().getCurrentTask(),Constants.tiktokPackageName);
        }
    }


    public void sendMsgToServer() {
        showLogAndTsPrint("向服务器发送获取的用户信息");
        MsgTaskBean msgTaskBean = UpdateInfoHandler.getInstance().getMsgTaskBean();
        if (msgTaskBean != null) {
            String jsonData = GsonUtils.toJson(msgTaskBean);
            LogUtils.v("向服务器发送最新获取的信息：");
            LogUtils.v(jsonData);
            //发送消息
            WebsocketUtil.getWebsocketUtil().sendMsg(jsonData);
        }
    }


    /**
     * type 默认为2----更新tiktok数据  5---更新手机已安装信息等
     * @param userInfo
     * @param type
     * @return
     */
    public MsgTaskBean createCurrentUpdateInfo(UserInfo userInfo,int type,boolean syncAccount) {
        //存储用户信息到本地缓存中
        String userJson=GsonUtils.toJson(userInfo);
        SPUtils.getInstance().put(UserInfo.class.getSimpleName(),userJson);
        MsgTaskBean msgTaskBean = new MsgTaskBean();
        msgTaskBean.setTaskType(currentTaskType);
        msgTaskBean.setCode(1003);
        msgTaskBean.setType(type);
        msgTaskBean.setToken(SPUtils.getInstance().getString("token"));
        PhoneAndLoginInfo phoneAndLoginInfo = new PhoneAndLoginInfo();
        List<AppInfo> apps = AppUtils.Companion.getAllApps(BaseApp.app.getApplicationContext());
        List<ApkInfo> currentInstallApps = convertToCurrentNeedApps(apps);
        for (int i = 0; i < currentInstallApps.size(); i++) {
            ApkInfo apkInfo = currentInstallApps.get(i);
            if (apkInfo.packageName.equals(taoSe)) {
                currentInstallApps.remove(i);
                i--;
                continue;
            }
            ApkStatus apkStatus = new ApkStatus();
            if (AppUtils.Companion.isAppInstall(BaseApp.app.getApplicationContext(), apkInfo.packageName)) {
                //当前应用已安装
                if (apkInfo.packageName.equals(Constants.tiktokPackageName)) {
                    //判断tiktok
                    apkStatus.setStatus(userInfo == null ? 1 : 2);
                    if (userInfo != null) {
                        apkStatus.setAccountList(userInfo.getAccountList());
                    }
                } else {
                    //其他应用默认未登录状态
                    apkStatus.setStatus(1);
                }
            } else {
                //当前应用未安装
                apkStatus.setStatus(0);
            }
            apkStatus.apkName = apkInfo.getApkName();
            apkStatus.versionCode = apkInfo.getApkVersion();
            apkStatus.versionName = apkInfo.getVersionName();
            if (apkInfo.getPackageName().equals(Constants.tiktokPackageName)) {
                apkStatus.setCurrentAccount(userInfo);
                phoneAndLoginInfo.getUserInfo().add(apkStatus);
            }
        }
        phoneAndLoginInfo.setCurrentInstallApps(currentInstallApps);
        phoneAndLoginInfo.setTaskType(currentTaskType);
        phoneAndLoginInfo.setSyncAccount(syncAccount);
        ServerInnerDataBean serverInnerDataBean = new ServerInnerDataBean();
        serverInnerDataBean.setJson(GsonUtils.toJson(phoneAndLoginInfo));
        msgTaskBean.setData(serverInnerDataBean);
        UpdateInfoHandler.getInstance().setMsgTaskBean(msgTaskBean);
        return msgTaskBean;
    }

    @NonNull
    private static List<ApkInfo> convertToCurrentNeedApps(List<AppInfo> apps) {
        List<ApkInfo> containsApp = new ArrayList<>();
        for (int i = 0; i < apps.size(); i++) {
            ApkInfo apkInfo = new ApkInfo();
            apkInfo.setApkName(apps.get(i).getApkName());
            apkInfo.setApkVersion(apps.get(i).getVersionCode());
            apkInfo.setPackageName(apps.get(i).getAppName());
            apkInfo.setVersionName(apps.get(i).getVersionName());
            containsApp.add(apkInfo);
        }
        return containsApp;
    }


    public int currentKeywordIndex;

    private void doKeywordsAutoLookVideo() throws InterruptedException {
        List<String> keywords = serverTaskDataBean.getSearchKeywords();
        long countSingleLookDuration = serverTaskDataBean.getDuration() / keywords.size();
        if (countSingleLookDuration < 2) {
            long keywordsSize = serverTaskDataBean.getDuration() / 2;
            if (keywordsSize == 0) {
                keywords = keywords.subList(0, 1);
            } else {
                keywords = keywords.subList(0, (int) keywordsSize);
            }
            countSingleLookDuration = 2;
        }
        currentKeywordIndex = 0;
        tickTokTaskDealTools.searchAndAutoLookVideo(currentKeywordIndex, keywords, countSingleLookDuration * 20 * 1000, serverTaskDataBean.getLikePercent(), serverTaskDataBean.getAttentionPercent(), serverTaskDataBean.getCommentPercent());
    }

    public void test() throws InterruptedException {
//        String result = AccessibilityTool.getInstance().findNodeInfoAllInPage("", null, service, "", false);
//        Message message= Message.obtain();
//        message.obj=result;
//        EventBus.getDefault().post(message);
//        onTaskFinish();
//        checkAndSendMessageToServer();
//        List<AccessibilityNodeInfo> nodeImages = AccessibilityTool.getInstance().findNodesByIdPlus(null, null, service, FindIdResouresConfig.verifyImageCodeImageNodeId);
//        if(tickTokTaskDealTools.isNodeExist(nodeImages)){
////            AccessibilityTool.getInstance().findNodeInfoAllInPage(nodeImage,service,"",false);
//        }else{
//            showLogAndTsPrint("未找到图片Node");
//            Thread.sleep(4000);
//            changeTaskStatusToStart();
//        }
//        tickTokTaskDealTools.swipeSeekBar("张三",false,0);
//        TsUtils.showTips("开始测试任务");
//        Thread.sleep(4000);
//        int x=ScreenUtils.getAppScreenWidth()/2;
//        int y=650;
//        AccessibilityTool.getInstance().clickScreen(service, x,y);
//        new Handler(Looper.getMainLooper()).post(new Runnable() {
//            @Override
//            public void run() {
//                ToastUtils.showShort("点击了屏幕:"+x+","+y);
//            }
//        });
        taskStatus = FINISH;
    }


public interface OnGetLoginStatus {
    void onGetLoginStatus(boolean isLogin);
}


}
